package com.ruoyi.gd.khxx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.gd.wgd.domain.ZWgd;
import com.ruoyi.gd.ywd.domain.ZYwd;
import com.ruoyi.gd.ywd.domain.vo.ZYwdVo;
import com.ruoyi.gd.ywdwgd.domain.ZYwdwgd;
import com.ruoyi.gd.ywdwgd.service.IZYwdwgdService;
import com.ruoyi.system.service.ISysDictTypeService;
import lombok.RequiredArgsConstructor;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.stereotype.Service;
import com.ruoyi.gd.khxx.domain.bo.ZKhxxBo;
import com.ruoyi.gd.khxx.domain.vo.ZKhxxVo;
import com.ruoyi.gd.khxx.domain.ZKhxx;
import com.ruoyi.gd.khxx.mapper.ZKhxxMapper;
import com.ruoyi.gd.khxx.service.IZKhxxService;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 客户信息Service业务层处理
 *
 * @author ruoyi
 * @date 2024-03-17
 */
@RequiredArgsConstructor
@Service
public class ZKhxxServiceImpl implements IZKhxxService {

    private final ZKhxxMapper baseMapper;

    @Resource
    private ISysDictTypeService dictTypeService;

    @Resource
    private IZYwdwgdService zywdwgdService;

    /**
     * 查询客户信息
     */
    @Override
    public ZKhxxVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询客户信息列表
     */
    @Override
    public TableDataInfo<ZKhxxVo> queryPageList(ZKhxxBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ZKhxx> lqw = buildQueryWrapper(bo);
        lqw.orderByDesc(ZKhxx::getPx);
        Page<ZKhxxVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询客户信息列表
     */
    @Override
    public List<ZKhxxVo> queryList(ZKhxxBo bo) {
        LambdaQueryWrapper<ZKhxx> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ZKhxx> buildQueryWrapper(ZKhxxBo bo) {
        LambdaQueryWrapper<ZKhxx> lqw = Wrappers.lambdaQuery();
        try {
            // 处理数据，去除前后空格
            bo.setKhname(StringUtils.trimField(bo, "khname"));

            LoginUser loginUser = LoginHelper.getLoginUser();
            // 1.通过字典数据，哪些用户可以获取所有数据
            List<String> khGetAllData = dictTypeService.selectDictDataByType("kh_getAllData").stream().map(SysDictData::getDictValue).collect(Collectors.toList());
            // 判断字典数据中的id在集合中是否存在
            boolean b = khGetAllData.stream().anyMatch(val -> val.equals(loginUser.getUserId().toString()));
            // 如果当前用户不存在则查询所有
            if (!b) {
                lqw.eq(true, ZKhxx::getCreateId, loginUser.getUserId());
            }
            lqw.like(StringUtils.isNotBlank(bo.getKhname()), ZKhxx::getKhname, bo.getKhname());
            lqw.like(StringUtils.isNotBlank(bo.getDz()), ZKhxx::getDz, bo.getDz());
            lqw.like(StringUtils.isNotBlank(bo.getSh()), ZKhxx::getSh, bo.getSh());
            lqw.eq(StringUtils.isNotBlank(bo.getXhkh()), ZKhxx::getXhkh, bo.getXhkh());
            lqw.eq(bo.getPx() != null, ZKhxx::getPx, bo.getPx());
            lqw.eq(StringUtils.isNotBlank(bo.getBz()), ZKhxx::getBz, bo.getBz());
//            lqw.eq(StringUtils.isNotBlank(bo.getWszt()), ZKhxx::getWszt, bo.getWszt());
            // 判断是否已开票
            if (StringUtils.isNotEmpty(bo.getWszt())) {  // 是否已下场
                List<String> strings = Arrays.asList(bo.getWszt().split(","));
                lqw.in(ZKhxx::getWszt, strings);
            }
            if(!"admin".equals(loginUser.getUsername())) {
                List<String> strings = Arrays.asList("0");
                lqw.in(ZKhxx::getDelFlag, strings);
                lqw.orderByAsc(ZKhxx::getDelFlag);
            }
            // 添加时间条件
            if (bo.getParams()!=null && bo.getParams().size() > 0) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Object start = bo.getParams().get("startTime");
                Object end = bo.getParams().get("endTime");
                if (null != start && null != end) {
                    Date startTime = format.parse((String) start);
                    Date endTime = format.parse((String) end);
                    if (startTime != null && endTime != null) {
                        lqw.ge(ZKhxx::getCreateTime, startTime);
                        lqw.le(ZKhxx::getCreateTime, endTime);
                    }
                }
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return lqw;
    }

    /**
     * 新增客户信息
     */
    @Override
    public Boolean insertByBo(ZKhxxBo bo) {
        ZKhxx add = BeanUtil.toBean(bo, ZKhxx.class);
        LoginUser loginUser = LoginHelper.getLoginUser();
        add.setCreateId(loginUser.getUserId()+"");
        if (!validEntityBeforeSave(add)) {
            throw new RuntimeException(add.getKhname() + " 客户已存在");
        }
        if (StringUtils.isEmpty(add.getSh())) {
            add.setWszt("1");
        }else {
            add.setWszt("2");
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改客户信息
     */
    @Override
    public Boolean updateByBo(ZKhxxBo bo) {
        ZKhxx update = BeanUtil.toBean(bo, ZKhxx.class);
//        if (!validEntityBeforeSave(update)) {
//            throw new RuntimeException("姓名已存在");
//        }
        // 判断当前的数据是否有税号，如果没有税号，则显示已完善 否则显示待完善
        if (StringUtils.isEmpty(update.getSh())) {
            update.setWszt("1");
        }else {
            update.setWszt("2");
            // 如果有税号，查询业务单，当前用户没有地址数据，如果没有的话，则批量更新
            int row = zywdwgdService.updateShByKhId(update.getId(), update.getSh());
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private boolean validEntityBeforeSave(ZKhxx entity){
        //TODO 做一些数据校验,如唯一约束
        QueryWrapper<ZKhxx> wrapper = new QueryWrapper<>();
        wrapper.eq("khname", entity.getKhname());
        wrapper.eq("del_flag", "0");
        Long aLong = baseMapper.selectCount(wrapper);
        return aLong == 0;
    }

    /**
     * 批量删除客户信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.batchDeleteIds(ids) > 0;
    }

    @Override
    public List<ZKhxxVo> queryListByIds(String ids) {
        String[] split = ids.split(",");
        List<ZKhxxVo> list = baseMapper.selectByIds(split);
        return list;
    }

    @Override
    public Boolean authData(String[] ids) {
        return baseMapper.updateBatchByIds(ids) > 0;
    }

    @Override
    public Boolean recoverData(List<String> asList) {
        return baseMapper.recoverData(asList) > 0;
    }

    @Override
    public Integer queryByMaxBh() {
        Integer i = baseMapper.queryByMaxBh();
        if (i == null) {
            i = 1;
        }else {
            i++;
        }
        return i;
    }

}
